import os
from main import Check_sys
import scipy
from logging import info, debug, warning, error
import pbcvt
import dip
import numpy as np
from celery import Celery
import logging
import coloredlogs
from read_info_from_excel import get_img_data

logger = logging.getLogger('your-module')
coloredlogs.install(level='DEBUG')
coloredlogs.install(level='DEBUG', logger=logger)

app = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost')

img_data = get_img_data()


@app.task
def add_image(img_path):
    def get_mask(img):
        if img.ndim == 3:
            img = img[:, :, 0]
        m = 1 - (img < 0.06)
        return scipy.ndimage.binary_erosion(m, np.ones((11, 11)), 10)

    img = dip.imread(image_path=img_path, resize=True)
    mask = get_mask(img)
    hemorrhage = pbcvt.hemorrhage_extract((img * 255).astype(np.uint8))
    hemorrhage_cal = hemorrhage[:, :, 0] == 0
    hemorrhage_cal *= mask
    # info('hemorrhage' + str(hemorrhage.shape))
    # plt.imshow(exudata, cmap='gray')
    # plt.show()
    exudata = pbcvt.exudate_extract((img * 255).astype(np.uint8))
    exudata_cal = exudata[:, :, 0] == 0
    exudata_cal *= mask
    # info('exudata' + str(exudata.shape))
    inf = dip.readInfo(dip.imread(img_path, resize=False))
    if inf['id'] == '':
        error(inf)
        return
    # if len(inf['id']) != 5:
    #     error('Error Number:' + inf['id'])
    # error(inf['id'])

    or_name = 'static/diag_result/%s_%s_or.jpg' % (inf['id'], inf['which_eye'])
    ha_name = 'static/diag_result/%s_%s_ha.jpg' % (inf['id'], inf['which_eye'])
    ex_name = 'static/diag_result/%s_%s_ex.jpg' % (inf['id'], inf['which_eye'])
    # error(or_name)
    scipy.misc.imsave(or_name, dip.imread(img_path, resize=False))
    scipy.misc.imsave(ex_name, exudata)
    scipy.misc.imsave(ha_name, hemorrhage)
    number = int(inf['id'])
    if not number in img_data.keys():
        error('Error handling ' + img_path)
        return ""
    # if img_data[number]['time'] != '2017-02-28':
    #     error(number)
    #     error(img_data[number]['time'])
    #     return

    check_sys, new_record = Check_sys.get_or_create(
        number="%05d" % number,
        which_eye=inf['which_eye'],
    )
    check_sys.name = img_data[number]['name']
    check_sys.number = "%05d" % number
    check_sys.created_date = img_data[number]['time']
    check_sys.which_eye = inf['which_eye']
    check_sys.original_image = or_name
    check_sys.ha_img = ha_name
    check_sys.ex_img = ex_name
    check_sys.ex_area = float(exudata_cal.sum() / 255)
    check_sys.ha_area = float(hemorrhage_cal.sum() / 255)
    check_sys.eye_sight = img_data[number]['left_sight'] if \
        inf['which_eye'] == 'L' else \
        img_data[number]['right_sight']
    check_sys.high_blood_pressure = img_data[number]['high_blood_pressure']
    check_sys.diabetes = img_data[number]['diabetes']
    check_sys.age = img_data[number]['age']
    check_sys.save()
    return ""
